from time import sleep

from common.ReadConfig import ConfigReader
from httprunner import HttpRunner,Config,RunTestCase,RunRequest,Step
from business.login_test import TestCaseLogin as Login  # 起别名，不然会识别成两条测试用例
base_path = ConfigReader('config.ini').get_value('dev_base_url')        # 项目的全局地址
class PerformAPI(HttpRunner):
    config = Config("start testing...").\
        base_url(base_path).\
        verify(False)
    teststeps = [
        Step(
            RunTestCase("登录").
            call(Login).
            export(*['token',])
             ),
    ]

def reset_token(token = Login):
    PerformAPI.teststeps.clear()        # 历史的token清除掉
    PerformAPI.teststeps.append(
        Step(
            RunTestCase("登录").
                call(token).
                export(*["token",])
        )
    )
    pass
"""
电商网站，会有不同的权限，不要把token写死了
后面可以灵活换其他的token
"""
headers = {"Authori-zation":"Bearer ${token}"}
def send_request(request_name,method,path,body = None,headers = headers):
    if method == 'get' or method == 'GET':
        return RunRequest(request_name).\
            get(path).\
            with_headers(**headers).\
            extract().\
            with_jmespath("body",'res_data')
    elif method =='post' or method == 'POST':
        return RunRequest(request_name).\
            post(path).\
            with_json(body).\
            with_headers(**headers).\
            extract().\
            with_jmespath("body",'res_data')
    elif method == 'put' or method == 'PUT':
        return RunRequest(request_name). \
            put(path). \
            with_headers(**headers). \
            extract(). \
            with_jmespath("body", 'res_data')
    elif method =='delete' or method == 'DELETE':
        return RunRequest(request_name). \
            delete(path). \
            with_headers(**headers). \
            extract(). \
            with_jmespath("body", 'res_data')
def Step_obj(obj):
    return Step(
        obj
    )

def get_last_response(obj:list):
    PerformAPI.teststeps.extend(obj)        # 追加所有的runrequests对象
    api = PerformAPI()
    sleep(1)
    api.test_start()
    res_data = api.with_export(['token','res_data']).get_export_variables()     # 把token以及res_data可以提取字典的形式，后续使用
    return res_data













